<template>
  <div class="analysis">
    <!-- 加载动画 -->
    <div v-if="loading" class="loading">加载中...</div>
    
    <!-- ECharts 容器 -->
    <div ref="chart" class="chart-container"></div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { getUserInfo } from "@/utils/auth";
import {ElMessage} from "element-plus";

const data = reactive({
  user: getUserInfo() || {},
  form: {},
  branchId: null,
  branchOptions: [],
})

const branchName = ref('') // 用于存储选择的党支部名称
const branchOptions = ref([]) // 存储所有的支部名称选项
const chart = ref(null)
const loading = ref(false) // 加载状态

// 查询数据
const loadData = async () => {
  loading.value = true // 开始加载数据，显示加载动画

  try {
    const res1 = request.get('organizationMember/selectById/' + data.user.id)
    const res = await request.get('/statiscalAnalysis/selectAll', { params: { branchId: (await res1).data.branchId} }) // 使用选择的支部名称查询
    if (res.code === '200') {
      const data = res.data // 假设返回的 data 是一个包含团员信息的数组
      const maleCount = data.filter(item => item.sex === '男').length
      const femaleCount = data.filter(item => item.sex === '女').length

      renderChart(maleCount, femaleCount, data.length)
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false // 数据加载完成后，隐藏加载动画
  }
}

// 渲染图表
const renderChart = (maleCount, femaleCount, totalCount) => {
  const myChart = echarts.init(chart.value)

  const option = {
    title: {
      text: '团员统计分析',
      subtext: `总数：${totalCount}人`,
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '性别比例',
        type: 'pie',
        radius: '50%',
        data: [
          { value: maleCount, name: '男' },
          { value: femaleCount, name: '女' }
        ]
      }
    ]
  }

  myChart.setOption(option)
}

onMounted(() => {
  loadData() // 初始化加载数据
})
</script>

<style scoped>
.analysis {
  padding: 20px;
}

/* 查询框样式 */
.el-select {
  width: 200px;
  margin-right: 10px;
}

.el-button {
  margin-left: 10px;
}

/* 加载动画样式 */
.loading {
  font-size: 20px;
  text-align: center;
  padding: 20px;
  color: #666;
  font-weight: bold;
}

/* ECharts容器样式 */
.chart-container {
  height: 400px;
  margin-top: 20px;
}
</style>
